package com.mars.pay.controller;

import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.mars.pay.common.PaymentTypeEnum;
import com.mars.pay.common.Result;
import com.mars.pay.entity.Order;
import com.mars.pay.service.AlipayService;
import com.mars.pay.service.OrderService;
import com.mars.pay.service.WechatPayService;
import com.mars.pay.utils.QRCodeUtil;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付控制器
 *
 * @author Mars
 */
@Slf4j
@Controller
@RequiredArgsConstructor
public class PaymentController {

    private final OrderService orderService;
    private final WechatPayService wechatPayService;
    private final AlipayService alipayService;

    /**
     * 微信支付页面
     */
    @GetMapping("/pay/wechat/{orderId}")
    public String wechatPay(@PathVariable Long orderId, Model model) {
        try {
            // 查询订单
            Order order = orderService.getByOrderId(orderId);
            if (order == null) {
                model.addAttribute("error", "订单不存在");
                return "error";
            }

            // 调用微信支付接口
            String codeUrl = wechatPayService.nativePay(order);

            // 生成二维码
            String qrCodeBase64 = QRCodeUtil.generateQRCodeBase64(codeUrl);

            // 传递数据到页面
            model.addAttribute("order", order);
            model.addAttribute("qrCode", qrCodeBase64);
            model.addAttribute("codeUrl", codeUrl);

            return "pay-wechat";
        } catch (Exception e) {
            log.error("微信支付失败", e);
            model.addAttribute("error", "微信支付失败：" + e.getMessage());
            return "error";
        }
    }

    /**
     * 支付宝支付页面
     */
    @GetMapping("/pay/alipay/{orderId}")
    public String alipayPay(@PathVariable Long orderId, Model model) {
        try {
            // 查询订单
            Order order = orderService.getByOrderId(orderId);
            if (order == null) {
                model.addAttribute("error", "订单不存在");
                return "error";
            }

            // 调用支付宝支付接口，获取支付表单
            String form = alipayService.pagePay(order);

            // 直接返回支付表单（HTML）
            return "redirect-form";
        } catch (Exception e) {
            log.error("支付宝支付失败", e);
            model.addAttribute("error", "支付宝支付失败：" + e.getMessage());
            return "error";
        }
    }

    /**
     * 支付宝支付（直接跳转）
     */
    @PostMapping("/pay/alipay/{orderId}")
    @ResponseBody
    public String alipayPayPost(@PathVariable Long orderId) {
        try {
            // 查询订单
            Order order = orderService.getByOrderId(orderId);
            if (order == null) {
                return "<html><body>订单不存在</body></html>";
            }

            // 调用支付宝支付接口，获取支付表单
            String form = alipayService.pagePay(order);

            // 返回支付表单，浏览器会自动提交
            return form;
        } catch (Exception e) {
            log.error("支付宝支付失败", e);
            return "<html><body>支付宝支付失败：" + e.getMessage() + "</body></html>";
        }
    }

    /**
     * 微信支付回调通知
     */
    @PostMapping("/notify/wechat")
    @ResponseBody
    public Map<String, String> wechatNotify(HttpServletRequest request) {
        Map<String, String> response = new HashMap<>();
        
        try {
            // 构建回调参数
            String timestamp = request.getHeader("Wechatpay-Timestamp");
            String nonce = request.getHeader("Wechatpay-Nonce");
            String signature = request.getHeader("Wechatpay-Signature");
            String serialNo = request.getHeader("Wechatpay-Serial");
            String body = request.getReader().lines()
                    .reduce("", (accumulator, actual) -> accumulator + actual);

            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(serialNo)
                    .nonce(nonce)
                    .signature(signature)
                    .timestamp(timestamp)
                    .body(body)
                    .build();

            // 处理回调
            boolean success = wechatPayService.handleNotify(requestParam);

            if (success) {
                response.put("code", "SUCCESS");
                response.put("message", "成功");
            } else {
                response.put("code", "FAIL");
                response.put("message", "失败");
            }
        } catch (Exception e) {
            log.error("处理微信支付回调异常", e);
            response.put("code", "FAIL");
            response.put("message", e.getMessage());
        }

        return response;
    }

    /**
     * 支付宝支付回调通知
     */
    @PostMapping("/notify/alipay")
    @ResponseBody
    public String alipayNotify(HttpServletRequest request) {
        try {
            // 获取所有回调参数
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            
            for (String name : requestParams.keySet()) {
                String[] values = requestParams.get(name);
                String valueStr = String.join(",", values);
                params.put(name, valueStr);
            }

            log.info("收到支付宝回调参数：{}", params);

            // 处理回调
            boolean success = alipayService.handleNotify(params);

            if (success) {
                return "success";
            } else {
                return "fail";
            }
        } catch (Exception e) {
            log.error("处理支付宝回调异常", e);
            return "fail";
        }
    }

    /**
     * 查询支付状态（微信）
     */
    @GetMapping("/pay/query/wechat/{orderNo}")
    @ResponseBody
    public Result<Transaction> queryWechatPayStatus(@PathVariable String orderNo) {
        try {
            Transaction transaction = wechatPayService.queryOrder(orderNo);
            return Result.success(transaction);
        } catch (Exception e) {
            log.error("查询微信支付状态失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询支付状态（支付宝）
     */
    @GetMapping("/pay/query/alipay/{orderNo}")
    @ResponseBody
    public Result<AlipayTradeQueryResponse> queryAlipayStatus(@PathVariable String orderNo) {
        try {
            AlipayTradeQueryResponse response = alipayService.queryOrder(orderNo);
            return Result.success(response);
        } catch (Exception e) {
            log.error("查询支付宝支付状态失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 通用查询支付状态
     */
    @GetMapping("/pay/query/{orderNo}")
    @ResponseBody
    public Result<Map<String, Object>> queryPayStatus(@PathVariable String orderNo) {
        try {
            Order order = orderService.getByOrderNo(orderNo);
            if (order == null) {
                return Result.error("订单不存在");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("order", order);
            result.put("statusDesc", getStatusDesc(order.getStatus()));

            return Result.success(result);
        } catch (Exception e) {
            log.error("查询支付状态失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取状态描述
     */
    private String getStatusDesc(Integer status) {
        return switch (status) {
            case 0 -> "待支付";
            case 1 -> "支付中";
            case 2 -> "支付成功";
            case 3 -> "支付失败";
            case 4 -> "已退款";
            case 5 -> "已关闭";
            default -> "未知状态";
        };
    }
}

